<?php
namespace app\small\controller;
use app\common\base\_Db;
use Endroid\QrCode\QrCode;
use qrc\Aes;
use think\Cache;
use think\Controller;
use think\Db;
use think\Log;
use vehicle\signvehicle;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/27
 * Time: 15:28
 */
class Drivercheck extends Controller{
    /*
     * 司机二维码
     */
    public function DriverQrc(){
        dump(strtotime('2018-12-06 15:09:39'));
        $uid = input('uid');
        $lineId = input('lineId');//身份
        $price = input('price');//身份
        //司机二维码
        $res=array(
            //'uid'       => (int)2084,
            'cardTime'  => (int)$uid,//传递uid
            'price'     => (int)$price,
            /*'DeviceId' =>'0431000018A00253',*/
            'line'      => (int)$lineId,
            'type'      => 'driver'
        );
        $res = json_encode($res);
        $aes = new Aes('1234567812345678');
        //加密
        $encrypted = $aes->encrypt($res);
        //dump($encrypted);
        $qrCode = new QrCode();
        ob_start();
        $qrCode ->setText($encrypted);
        //$qrCode  ->setSize(300);//大小
        $qrCode ->setLabelFontPath(VENDOR_PATH.'endroid/qrcode/assets/fonts/noto_sans.otf');
        $qrCode ->setErrorCorrectionLevel('high');
        $qrCode ->setLabelFontSize(16);
        header('Content-Type: '.$qrCode->getContentType());
        $png = $qrCode->writeString();
        $imageString = base64_encode($png);
        ob_end_clean();
        $Img =  'data:image/png;base64,'.$imageString;
        return 'data:image/png;base64,'.$imageString;
        //return json_encode($Img);
        //return '<img src="data:image/png;base64,'.$imageString.'">';
    }
    /*
     * 司机绑定线路及车辆
     * 按线路同一设备二十分钟绑定一个人
     * 二十分钟后重新绑定
     */
    //在home->InterApi
    public function Bind(){
        $JsonData = file_get_contents('php://input');
        //$JsonData = json_decode($JsonData,true);
        $aes = new Aes('1234567812345678');
        $encrypted = $aes->decrypt($JsonData);
        $JsonData = json_decode($encrypted,true);
        $uid = $JsonData['uid'];
        $DeviceId = $JsonData['DeviceId'];//设备号
        $day_time = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $driver_bus = Db::table('bus_driver')
            ->where('deviceid = "'.$DeviceId .'" and oper_time >= "'.$day_time.'"')->order('oper_time desc')->limit(1)->find();
        if (!empty($uid)&&$driver_bus['staff_id'] == $uid){
            return json_encode(['code'=>'1000','msg'=>'线路已切换']);
        }
        if (empty($driver_bus)||(!empty($driver_bus)&&(time()-$driver_bus['oper_time'])>1200)){
            switch ($JsonData['type']){
                case 'driver':
                    //根据线路id更新其他信息
                    if(
                        Db::table('bus_info')
                        ->where('vehicle_device_id ="'.$JsonData['DeviceId'].'"')
                        ->update([
                            'line_id'   =>$JsonData['line'],
                            'oper_date' =>date('Y-m-d H:i:s',time())
                        ])
                    ){
                        //先查询再绑定
                        /*司机绑定线路及车辆,按线路同一设备二十分钟绑定一个人,二十分钟后重新统计*/
                        Db::table('bus_driver')
                            ->insert([
                                'deviceid'    =>$JsonData['DeviceId'],
                                'staff_id'    =>$JsonData['uid'],
                                'oper_time'   =>time(),
                            ]);

                        return json_encode(['code'=>'200','msg'=>'切换线路成功']);
                    }else{
                        return json_encode(['code'=>'1000','msg'=>'切换线路失败']);
                    }
                    break;
            }
        }elseif((time()-$driver_bus['oper_time'])<1200){
            return json_encode(['code'=>'1000','msg'=>'二十分钟内已有司机切换线路']);
        }else{
            return json_encode(['code'=>'1000','msg'=>'切换线路失败']);
        }
    }
    /*
     * 司机点击到站功能
     * 查询是否绑定车辆
     */
    public function Arrival(){
        $uid = input('uid');
        $day_time = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $driver_bus = Db::table('bus_driver')->field('id,deviceid,staff_id,oper_time,arr_time')
            ->where('staff_id = '.$uid )->order('oper_time desc')->limit(1)->select();
        if (!empty($driver_bus)){
            //车辆到站可重复点击更新
            $res = Db::table('bus_driver')->where('id = '.$driver_bus[0]['id'] )->update(['arr_time'=>time()]);
            if ($res){
                return $this->RidInfo($uid);
            }else{
                return json_encode(['code'=>'0','msg'=>'点击失败']);
            }
        }else{
            return json_encode(['code'=>'0','msg'=>'未绑定车辆不能进行到站功能操作']);
        }
    }
    /*
     * 司机绑定车辆已检票人员情况
     * 查询是否绑定车辆
     */
    public function  CheckInfo(){
        $uid = input('uid');
        return $this->RidInfo($uid);
    }
    /*
     * 乘车记录统计
     */
    public function  RidInfo($uid){
        $day_time = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $now_day = date('Y-m-d',$day_time).' 00:00:00"';
        //计算最近两趟车辆
        $driver_bus = Db::table('bus_driver')->field('id,deviceid,staff_id,oper_time,arr_time')
            ->where('staff_id = '.$uid )->order('oper_time desc')->limit(2)->select();
        //echo Db::table('')->getLastSql();
        //旅客（order_info）
        $where_user = 'deviceid = "'.$driver_bus[0]['deviceid'].'"';
        //机场职工（free_order）
        $where_air = 'iden = 2 and deviceid ="'.$driver_bus[0]['deviceid'].'"';
        //专业化职工（free_order）
        $where_spe = 'iden = 3 and deviceid ="'.$driver_bus[0]['deviceid'].'"';
        if (!empty($driver_bus)){
            $beg_time = date('Y-m-d H:i:s',$driver_bus[0]['arr_time']);
            $oper_beg_time = date('Y-m-d H:i:s',$driver_bus[0]['oper_time']);
            //该司机只有一条到站记录
            if (count($driver_bus)==1){
                if (!empty($driver_bus[0]['arr_time'])){
                    $where_user .= ' and pay_time <"'.$beg_time.'"';
                    $where_air  .= ' and time <"'.$beg_time.'"';
                    $where_spe  .= ' and time <"'.$beg_time.'"';
                }else{
                    $where_user .= ' and pay_time >"'.$now_day.'"';
                    $where_air  .= ' and time >"'.$now_day.'"';
                    $where_spe  .= ' and time >"'.$now_day.'"';
                }
            }
            //存在两条到站记录
            elseif (count($driver_bus)==2){
                $end_time = date('Y-m-d H:i:s',$driver_bus[1]['arr_time']);
                $oper_end_time = date('Y-m-d H:i:s',$driver_bus[1]['oper_time']);
                if (!empty($driver_bus[0]['arr_time'])&&!empty($driver_bus[1]['arr_time'])){
                    $where_user .= ' and pay_time between "'.$end_time. '" and "'.$beg_time.'"';
                    $where_air  .= ' and time between "'.$end_time. '" and "'.$beg_time.'"';
                    $where_spe  .= ' and time between "'.$end_time. '" and "'.$beg_time.'"';
                }elseif($driver_bus[0]['arr_time'] != ''&&$driver_bus[1]['arr_time'] == ''){
                    $where_user .= ' and pay_time between "'.$oper_beg_time. '" and  "'.$beg_time.'"';
                    $where_air  .= ' and time between "'.$oper_beg_time. '" and  "'.$beg_time.'"';
                    $where_spe  .= ' and time between "'.$oper_beg_time. '" and  "'.$beg_time.'"';
                }elseif ($driver_bus[0]['arr_time'] == ''&& $driver_bus[1]['arr_time'] != ''){
                    $where_user .= ' and pay_time between "'.$oper_end_time. '" and  "'.$end_time.'"';
                    $where_air  .= ' and time between "'.$oper_end_time. '" and  "'.$end_time.'"';
                    $where_spe  .= ' and time between "'.$oper_end_time. '" and  "'.$end_time.'"';
                }elseif (empty($driver_bus[0]['arr_time'])&&empty($driver_bus[1]['arr_time'])){
                    $where_user .= ' and pay_time between "'.$oper_end_time. '" and  "'.$oper_beg_time.'"';
                    $where_air  .= ' and time between "'.$oper_end_time. '" and  "'.$oper_beg_time.'"';
                    $where_spe  .= ' and time between "'.$oper_end_time. '" and  "'.$oper_beg_time.'"';
                }
            }
            $res_user = count(Db::table('order_info')->where($where_user)->select());
            $res_air = count(Db::table('free_order')->where($where_air)->select());
            $res_spe = count(Db::table('free_order')->where($where_spe)->select());
            //查询该车辆座位数
            $bus_seat = Db::table('bus_info')->field('bus_seat')->where('vehicle_device_id ="'.$driver_bus[0]['deviceid'].'"')->find();
            $data['bus_seat'] =  $bus_seat['bus_seat'];
            $data['res_user'] =  $res_user;
            $data['res_air'] =  $res_air;
            $data['res_spe'] =  $res_spe;
            return json_encode($data);
        }else{
            return json_encode(['code'=>'0','msg'=>'未绑定车辆不能查看当前车检票情况']);
        }
    }
    /*
     * 司机扫码检票
     * 查询是否绑定车辆
     */
    public function CheckMoney(){
        $uid = input('uid');
        $day_time = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $driver_bus = Db::table('bus_driver')->field('id,deviceid,staff_id,oper_time')
            ->where('staff_id = '.$uid .' and oper_time >= "'.$day_time.'"')->order('oper_time desc')->limit(1)->select();
        $qrData = input('qrData');
        $fileName = str_replace("2B%","+",$qrData);
        //Log::write($qrData);
        $aes = new Aes('1234567812345678');
        //解密
        $dencrypted = $aes->decrypt($fileName);
        /*dump($dencrypted);exit();*/
        $JsonData = json_decode($dencrypted,true);
        $line = Db::table('bus_info')->field('line_id as line')->where('vehicle_device_id = "'.$driver_bus[0]['deviceid'].'"')->find();
        $price = Db::table('line')->field('price')->where('line_id ='.$line['line'])->find();
        if (!empty($driver_bus)){
            switch ($JsonData['type']){
                case 'post':
                    if($JsonData['iden'] == (int)2||$JsonData['iden'] == (int)4){
                        //是员工的状态下
                        //不允许一个员工在单位时间内多次刷卡，时间间䣓暂定30分钟
                        $res = Db::table('free_order')
                            ->where('iden = 2 and uid = '.$JsonData['uid'].' and time >"'.date('Y-m-d',$day_time).' 00:00:00"')
                            ->order('time desc')->limit(1)->select();

                        if (!empty($res) && (time()-strtotime($res[0]['time'])<1800)){
                            return json_encode(['code'=>'0','msg'=>'不允许重复刷卡']);
                        }
                        $data = [
                            'uid'=>$JsonData['uid'],
                            'iden'=>(int)2,
                            'money'=>(int)$price,
                            'line_id'=>(int)$line,
                            'time'=>date('Y-m-d H:i:s',time()),
                            'deviceid'=>$driver_bus[0]['deviceid']
                        ];
                        if( Db::name('free_order')->insert($data) ){
                            return json_encode(['code'=>'0','msg'=>'扫码成功']);
                        }else{
                            return json_encode(['code'=>'0','msg'=>'扫码失败']);
                        }
                    }elseif($JsonData['iden'] == (int)1){
                        //客户免密支付
                        if(time() - $JsonData['cardTime'] > 60){
                            return json_encode(['code'=>'0','msg'=>'扫码失败']);
                        }
                        $res = $this->payapply($JsonData['uid'],$JsonData['OutTradeNo'],$JsonData['price']*100);
                        if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
                            Db::name('order_info')
                                ->insert(
                                    [
                                        'pay_money'=>$price,
                                        'line_id'=>(int)$line,
                                        'deviceid'=>$driver_bus[0]['deviceid'],
                                        'out_trade_no'=>$JsonData['OutTradeNo'],
                                        'openid'=>$this->GetOpenId($JsonData['uid']),
                                        'pay_time'=>date('Y-m-d H:i:s',time()),
                                        'trade_state'=>(int)2
                                    ]
                                );
                            return json_encode(['code'=>'1','msg'=>'扫码成功']);
                        }else{
                            return json_encode(['code'=>'0','msg'=>'扫码失败']);
                        }
                    }elseif ($JsonData['iden'] == (int)3){
                        //不允许一个员工在单位时间内多次刷卡，时间间䣓暂定30分钟
                        $res = Db::table('free_order')
                            ->where('iden = 3 and uid = '.$JsonData['uid'].' and time >"'.date('Y-m-d',$day_time).' 00:00:00"')
                            ->order('time desc')->limit(1)->select();
                        if (!empty($res) && (time()-strtotime($res[0]['time'])<1800)){
                            return json_encode(['code'=>'0','msg'=>'不允许重复刷卡']);
                        }
                        $data = [
                            'uid'=>$JsonData['uid'],
                            'iden'=>(int)3,
                            'money'=>(int)$price,
                            'line_id'=>(int)$line,
                            'time'=>date('Y-m-d H:i:s',time()),
                            'deviceid'=>$driver_bus[0]['deviceid']
                        ];
                        if(Db::name('free_order')->insert($data)){
                            return json_encode(['code'=>'1','msg'=>'扫码成功']);
                        }else{
                            return json_encode(['code'=>'0','msg'=>'扫码失败']);
                        }
                    }
                    break;
            }
        }else{
            return json_encode(['code'=>'0','msg'=>'未绑定车辆不能检票']);
        }
    }
    //BUG申请扣费
    public function payapply($uid,$orderno,$money){
        $result = _Db::GetData('user',array('user_id'=>'uid','openid'=>'openid','sign_contract_id'=>'sign_contract_id'),'user_id = '.$uid);
        $url = 'https://api.mch.weixin.qq.com/transit/partnerpay/payapply';
        $scene_info=[
            'start_time'=>date('YmdHis'),  //扣费时间
        ];
        $post_data = [
            'appid'=>pay_config()['appid'], //服务商appid
            'mch_id'=>pay_config()['mch_id'], // 服务商商户号
            'sub_mch_id'=>pay_config()['sub_mch_id'], //子商户号
            'nonce_str'     =>'5K8264ILTKCHCQ5011SI8ZNMTM67VS', //
            'sign_type'     =>'HMAC-SHA256', //签名类型
            'body' =>'公交代扣',  //商品描述
            'out_trade_no'=>$orderno,  //订单号
            'total_fee'=>$money,  //金额
            'spbill_create_ip'=>'0.0.0.0', //终端IP
            'notify_url'=>'https://zf.ccairport.cn/home/interapi/back_notify', //回调通知url
            'trade_type'=>'PAP', //交易类型
            'contract_id'=>$result['sign_contract_id'], //扣费协议号
            'trade_scene'=>'BUS', //场景信息
            'scene_info'=>json_encode(['scene_info'=>$scene_info],JSON_UNESCAPED_UNICODE),
        ];
        $method = 'HMAC-SHA256'; //通过md5方式签名
        $post_data = signvehicle::sign($post_data,'AF7M2HpBiYpibtXGy7RpBm3pTZGr9rzf',$method);
        $curlPost = signvehicle::build($post_data);
        $data = signvehicle::curl_post($url,$curlPost);
        $res =signvehicle::toArray($data);
        return $res;
    }
    public function GetOpenId($id){
        $res = Db::name('user')
            ->field('openid')
            ->where('user_id ='.$id)
            ->find();
        return $res['openid'];
    }
    //扣费回调地址
    public function back_notify(){
        $xml=file_get_contents('php://input', 'r');
        //  Log::write(json_encode($xml,JSON_UNESCAPED_UNICODE),'error');
        $data = signvehicle::toArray($xml);
        $data_sign=$data['sign'];
        // sign不参与签名
        unset($data['sign']);
        $sign= signvehicle::sign($data,pay_config()['key'],$data['sign_type']);
        Cache::set('sign',$sign);
        // 判断签名是否正确  判断支付状态
        if($sign["sign"]===$data_sign){
            $result=true;
        }else{
            $result=false;
        }
        if($result){
            //更新用户订单状态
            Db::name('order_info')
                ->where('out_trade_no ='.$data['out_trade_no'])
                ->update(['trade_state'=>(int)2]);
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA]></return_msg></xml>';
        }else{
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;
    }
}